#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <strings.h>
#include <string.h>

int main(int argc,char *argv[]){

    if(argc < 3){
        fprintf(stderr,"Usage argc ... \n");
        exit(-1);
    }  

    // 得到通信文件描述符
    int cfd = socket(PF_INET,SOCK_STREAM,0);
    if (cfd < 0){
        fprintf(stderr,"socket error\n");
        exit(-1);
    }

    // 连接
    struct sockaddr_in ser_addr;
    bzero(&ser_addr,sizeof(ser_addr));
    ser_addr.sin_family = AF_INET;
    ser_addr.sin_addr.s_addr = inet_addr(argv[1]);
    ser_addr.sin_port = htons(atoi(argv[2]));
    if(connect(cfd,(struct sockaddr *)&ser_addr,sizeof(ser_addr)) < 0){
        fprintf(stderr,"connect error\n");
        exit(-1);
    }
    
    // 通信
    char buf[1024];
    while (1){
        memset(buf,'\0',sizeof(buf));
        fputs("Input message(q is quit): ",stdout);
        fgets(buf,sizeof(buf),stdin);
        if (!strcmp(buf,"q\n") || !strcmp(buf,"Q\n")){
            break;
        }

        write(cfd,buf,strlen(buf));
        read(cfd,buf,sizeof(buf));
        printf("Get message from server: %s\n",buf);
    }
    
    close(cfd);
    return 0;
}